package com.ciwong.epaper.modules.me.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.SelectObject;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.Member;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.mobilelib.utils.ViewHolder;
import com.ciwong.mobilelib.widget.CWDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * Created by neo on 2016/7/1.
 */
public class ClassListAdapterSpecific extends BaseAdapter {

    /**
     * 上下文对象
     */
    private Context mContext;

    /**
     * 班级信息集
     */
    private List<Clazz> mSelectObjects;

    /**
     * 默认选择的班级
     */
    private Clazz mSelectObject;


    /**
     * 要更改替换的班级
     */
    private Clazz mFromClass;

    private  int mJumpType;

    /**
     * 构造函数
     *
     * @param context
     *            上下文对象
     * @param selectObjects
     *            班级信息集
     * @param mSelectObject
     *            当前选中的学校信息
     */
    public ClassListAdapterSpecific(Context context, List<Clazz> selectObjects,
                                   int jumpType, Clazz mSelectObject,Clazz fromClass)
    {
        this.mContext = context;
        this.mSelectObjects = selectObjects;
        this.mSelectObject = mSelectObject;
        this.mJumpType=jumpType;
        mFromClass=fromClass;
    }

    @Override
    public int getCount()
    {
        return mSelectObjects != null ? mSelectObjects.size() : 0;
    }

    @Override
    public Object getItem(int position)
    {
        return mSelectObjects != null && !mSelectObjects.isEmpty()
                ? mSelectObjects.get(position) : null;
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View v;
        if (convertView == null)
        {
            v = View.inflate(mContext, R.layout.item_class, null);
        }
        else
        {
            v = convertView;
        }


        TextView tvClassName = ViewHolder.get(v, R.id.tv_item_class);
        TextView tv_teacher_name = ViewHolder.get(v, R.id.tv_teacher_name);

        TextView tv_school_name = ViewHolder.get(v, R.id.tv_school_name);

        ImageView iv_class_avatar= ViewHolder.get(v, R.id.iv_class_avatar);
        ImageView iv_arrow_right= ViewHolder.get(v, R.id.iv_arrow_right);
        Button btn_join_class=ViewHolder.get(v, R.id.btn_join_class);
        SelectObject selectObject = (SelectObject) getItem(position);
        tvClassName.setText(selectObject.getName() );

        if(null !=  mSelectObjects.get(position).getMembers() && mSelectObjects.get(position).getMembers().size()>0)
        {
            List<Member> memberList=mSelectObjects.get(position).getMembers();
            Member managerMem=null;
            for (Member member : memberList) {
                if (member.getRote() == EpaperConstant.USER_ROLE_TEACHER && member.getIsAdmin() == 1) {
                    managerMem=member;
                    break;
                }
            }
            if (null != managerMem) {
                tv_teacher_name.setText(managerMem.getUserName());
            }

        }else {
            tv_teacher_name.setVisibility(View.GONE);
        }


        if(null != mSelectObjects.get(position).getSchoolName())
        {
            tv_school_name.setText(mSelectObjects.get(position).getSchoolName());
        }else {
            tv_school_name.setVisibility(View.GONE);
        }


        String classAvatar = mSelectObjects.get(position).getClassAvatar();
        classAvatar = TextUtils.isEmpty(classAvatar) ? "drawable://" + R.drawable.about_icon
                : classAvatar;
        ImageLoader.getInstance().displayImage(classAvatar, iv_class_avatar,
                EConstants.getDefAvatarCircleBuilder());
        final int posi=position;


        if (mJumpType == IntentValue.JumpToJoinClassType.TYPE_JOIN_CLASS || mJumpType == IntentValue.JumpToJoinClassType.TYPE_CHANGE_CLASS  || mJumpType == IntentValue.JumpToJoinClassType.FROM_CLASS_LIST) {
            btn_join_class.setVisibility(View.VISIBLE);
            btn_join_class.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Clazz clazz = mSelectObjects.get(posi);
                    if (clazz != null)
                    {
                        CWDialog dialog = new CWDialog(
                                mContext);
                        dialog.setTitle("提示");
                        dialog.setMessage(mContext.getString(R.string.str_jion_class_confrim_hint_head)+clazz.getClassName()+","+
                                mContext.getString(R.string.str_jion_class_confrim_hint_tail));
                        dialog.setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which)
                                    {
                                        dialog.dismiss();
                                        joinClassById(clazz);
//                                        joinClass(applyCode);
                                    }
                                });
                        dialog.setNegativeButton(android.R.string.cancel,
                                null);
                        dialog.setCancelable(false);
                        dialog.show();
                    }
                }
            });
            iv_arrow_right.setVisibility(View.GONE);
        }else {
            btn_join_class.setVisibility(View.GONE);
            iv_arrow_right.setVisibility(View.VISIBLE);
        }
        return v;
    }

    public void clear()
    {
        if (this.mSelectObjects != null || !this.mSelectObjects.isEmpty())
        {
            this.mSelectObjects.clear();
            notifyDataSetChanged();
        }
    }

    public void addAll(List<Clazz> clazzs)
    {
        if (this.mSelectObjects != null)
        {
            this.mSelectObjects.addAll(clazzs);
            notifyDataSetChanged();
        }
    }



    public SelectObject getSelectObject()
    {
        return mSelectObject;
    }

    public void setSelectObject(Clazz selectObject)
    {
        this.mSelectObject = selectObject;
        notifyDataSetChanged();
    }



    private void joinClassById(final Clazz clazz) {

        //第一次加班fromClassId默认是0
        long fromClassId=0;
        if (mFromClass != null) {
            fromClassId = mFromClass.getId();
        }

        MeDao.getInstance().joinClassById(EApplication.BRAND_ID, EpaperConstant.USER_ROLE_STUDENT, fromClassId, clazz.getId(), new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId()+"") {


            @Override
            public void failed(int errorCode, Object data) {
                if (null != data && data.toString().equals("已经是该班级成员")) {
                    DialogUtil.showTopHintDialog(mContext,"你已经是该班成员，请勿重复添加！",-1);
                }else {
                    DialogUtil.showTopHintDialog(mContext,data.toString(),-1);
                }

            }
            @Override
            public void failed(Object data) {
            }

            @Override
            public void success(Object data) {
                //关掉当前页面，回到用户的班级列表并刷新！
                Toast.makeText(mContext, mContext.getString(R.string.str_join_class_success), Toast.LENGTH_LONG).show();
                Activity activity = (Activity) mContext;

                //更新本地缓存班级信息
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, clazz);
                ((EApplication)activity.getApplication()).setClazz(clazz);
                activity.sendBroadcast(new Intent(EpaperConstant.BROADCAST_CLASS_CHANGE));

                activity.setResult(Activity.RESULT_OK);

                activity.finish();

            }
        });
    }



}
